package com.fileTest;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
import com.util.DBConn;
import com.util.FileManager;

public class FileTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		process(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		process(request, response);
	}

	protected void process(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		req.setCharacterEncoding("UTF-8");

		Connection conn = DBConn.getConnection();
		String cp = req.getContextPath();
		String uri = req.getRequestURI();

		String root = getServletContext().getRealPath("/");
		String path = root + File.separator + "pds" + File.separator
				+ "saveFile";

		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		if (uri.indexOf("write.do") != -1) {
			forward(req, resp, "/fileTest/write.jsp");
		} else if (uri.indexOf("write_ok.do") != -1) {
			String encType = "UTF-8";
			int maxSizeFile = 5 * 1024 * 1024;

			MultipartRequest mr = new MultipartRequest(req, path, maxSizeFile,
					encType, new DefaultFileRenamePolicy());

			// 업로드한 파일이 존재하면 DB에 기록
			if (mr.getFile("uploadFile") != null) {
				FileTestDAO dao = new FileTestDAO(conn);
				int maxNum = dao.getMaxNum();
				FileTestDTO dto = new FileTestDTO();
				dto.setNum(maxNum + 1);
				dto.setSubject(mr.getParameter("subject"));
				dto.setSaveFileName(mr.getFilesystemName("uploadFile"));
				dto.setOriginalFileName(mr.getOriginalFileName("uploadFile"));

				dao.insertData(dto);
			}

			resp.sendRedirect(cp + "/file/list.do");
		} else if (uri.indexOf("list.do") != -1) {
			FileTestDAO dao = new FileTestDAO(conn);
			List<FileTestDTO> lists = dao.getLists();

			String downloadPath = cp + "/file/download.do";
			String deletePath = cp + "/file/deleted.do";

			req.setAttribute("lists", lists);
			req.setAttribute("downloadPath", downloadPath);
			req.setAttribute("deletePath", deletePath);

			forward(req, resp, "/fileTest/list.jsp");
		} else if (uri.indexOf("deleted.do") != -1) {
			int num = Integer.parseInt(req.getParameter("num"));
			FileTestDAO dao = new FileTestDAO(conn);
			FileTestDTO dto = dao.getReadData(num);

			FileManager.doFileDelete(dto.getSaveFileName(), path);
			dao.deleteData(num);
			resp.sendRedirect(cp + "/file/list.do");
		} else if (uri.indexOf("download.do") != -1) {
			int num = Integer.parseInt(req.getParameter("num"));
			FileTestDAO dao = new FileTestDAO(conn);
			FileTestDTO dto = dao.getReadData(num);

			if (dto == null) {
				return;
			}

			boolean flag = FileManager.doFileDownload(resp,
					dto.getSaveFileName(), dto.getOriginalFileName(), path);
			
			if (flag == false) {
				resp.setContentType("text/html;charset=\"utf-8\"");
				PrintWriter out = resp.getWriter();
				out.print("<script type='text/javascript'>");
				out.print("alert('download error...;);");
				out.print("</script>");
			}
		}
	}

	protected void forward(HttpServletRequest req, HttpServletResponse resp,
			String url) throws ServletException, IOException {
		// TODO Auto-generated method stub
		RequestDispatcher rd = req.getRequestDispatcher(url);
		rd.forward(req, resp);
	}
}
